package cn.tsoft.common
{
	import flash.display.DisplayObject;
	
	import mx.containers.Box;
	import mx.controls.ProgressBar;
	import mx.controls.ProgressBarMode;
	import mx.core.Container;
	import mx.managers.PopUpManager;

	public class ProgressBarMonitor implements IProgressMonitor
	{
		private static var _singleton:IProgressMonitor = null;
		private var _control:ProgressBar;
		private var _container:Container;
		private var _tokens:Array;
		private var _topmost:IMonitorToken ;
		
		public static function get singleton():IProgressMonitor{
			if(_singleton==null){
				_singleton = new ProgressBarMonitor();
			}
			return _singleton;
		}
		
		
		public function ProgressBarMonitor()
		{
			_tokens = new Array();
			_container = new Box();
			_container.setStyle("modalTransparency",0.0);
			_container.setStyle("modalTransparencyBlur",0);
			_control = new ProgressBar();
			_control.width = 250;
			_control.labelPlacement="center";
			_control.indeterminate = true;
			_control.setStyle("fontSize",12);
			_control.setStyle("trackHeight",20);
			_control.setStyle("color",0x663333);
			_control.minimum =0;
			_control.maximum =100;
			_container.addChild(_control);
		}

		public function begin(target:Object, parent:DisplayObject, cancelHandler:Function=null):IMonitorToken
		{
			if(parent==null) throw new Error("parent can not be null");
			var token:MonitorToken = new MonitorToken(this,target,parent,cancelHandler);
			show(token);
			_tokens.push(token);
			return token;
		}
		
		
		private function show(token:IMonitorToken):void{
			hide();
			if(token){
				_topmost = token;
				_control.label = token.label;
				if(!_container.isPopUp){
					PopUpManager.addPopUp(_container,token.parent,true);
					PopUpManager.centerPopUp(_container);
					PopUpManager.bringToFront(_container);
				}
			}
		}
		
		public function update(token:IMonitorToken, curValue:Number,label:String):void
		{
			if(token){
				if(curValue>-1)token.curValue = curValue;
				if(label)token.label = label;
				if(_topmost==token){
					_control.label = token.label;
					_control.minimum = token.minValue;
					_control.setProgress(token.curValue,token.maxValue);
				}
			}
		}
		
		public function stop(token:IMonitorToken):void
		{
			if(token){
				if(removeToken(token)){
					if(_tokens.length==0){
						hide();
					}else if(_topmost==token){
						_topmost = _tokens[_tokens.length-1]
						show(_topmost);
					}
				}
			}
		}
		
		
		private function hide():void{
			if(_container.isPopUp){
				PopUpManager.removePopUp(_container);
			}
		}
		
		
		private function removeToken(token:IMonitorToken):Boolean{
			var index:int = _tokens.indexOf(token);
			if(index>=0){
				_tokens.splice(index,1);
				return true;
			}
			return false;
		}
		
	}
}